//
//  CustomRecorder.m
//  RecorderView
//
//  Created by 明意 on 2021/7/21.
//  Copyright © 2021 Facebook. All rights reserved.
//

#import "CustomRecorder.h"
#import <AVFoundation/AVFoundation.h>

@interface CustomRecorder()

@property (nonatomic, strong) AVAudioRecorder *recorder;


@end

@implementation CustomRecorder

- (instancetype)init
{
    self = [super init];
    if (self) {

    }
    return self;
}


#pragma mark override

- (void)dealloc {
    NSLog(@"CustomRecorder 被释放了");
}

#pragma mark init
- (void)initAudioRecorder{
    NSMutableDictionary *audioSetting = [NSMutableDictionary dictionary];

    // 设置录音格式 kAudioFormatMPEGLayer3设置貌似是没用的 默认设置就行
//    [audioSetting setObject:@(kAudioFormatMPEGLayer3) forKey:AVFormatIDKey];

    // 设置录音采样率，8000 44100 96000，对于一般录音已经够了
    [audioSetting setObject:@(44100) forKey:AVSampleRateKey];

    // 设置通道 1 2
    [audioSetting setObject:@(1) forKey:AVNumberOfChannelsKey];

    // 每个采样点位数,分为8、16、24、32
    [audioSetting setObject:@(16) forKey:AVLinearPCMBitDepthKey];

    // 是否使用浮点数采样 如果不是MP3需要用Lame转码为mp3的一定记得设置NO！(不然转码之后的声音一直都是杂音)
    // 是否使用浮点数采样 如果不是MP3需要用Lame转码为mp3的一定记得设置NO！(不然转码之后的声音一直都是杂音)
    // 是否使用浮点数采样 如果不是MP3需要用Lame转码为mp3的一定记得设置NO！(不然转码之后的声音一直都是杂音)

    [audioSetting setObject:@(YES) forKey:AVLinearPCMIsFloatKey];

    // 录音质量
    [audioSetting setObject:@(AVAudioQualityHigh) forKey:AVEncoderAudioQualityKey];


    NSString *fileName = @"audio.wav";
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    _filePath = [NSString stringWithFormat:@"%@/%@", docDir, fileName];
    NSURL *url = [NSURL fileURLWithPath:self.filePath];

    NSError *error;

    self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:audioSetting error:&error];

    if(error) {
        NSLog(@"Ups, could not create recorder %@", error);
        return;
    }
    // 0. 设置录音会话
    /**
     *  AVAudioSessionCategoryPlayAndRecord: 可以边播放边录音(也就是平时看到的背景音乐)
     */
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    //启动会话
    [[AVAudioSession sharedInstance] setActive:YES error:nil];

    if (error) {
        NSLog(@"Error setting category: %@", [error description]);
    }


}

#pragma mark public
- (void)startRecord{
    if (self.recorder){
        [self.recorder stop];
        self.recorder = nil;
        [self initAudioRecorder];
    } else {
        [self initAudioRecorder];
    }
    [self.recorder prepareToRecord];
    [self.recorder setMeteringEnabled:YES];
    [self.recorder record];

}
- (void)stopRecord{

    [self.recorder stop];
}

- (CGFloat)updateMeters
{
//    NSLog(@"update Meters");
    [self.recorder updateMeters];
    CGFloat normalizedValue = [self normalizedPowerLevelFromDecibels:[self.recorder averagePowerForChannel:0]];

    return normalizedValue;
}

#pragma mark private
- (CGFloat)normalizedPowerLevelFromDecibels:(CGFloat)decibels
{
//    if (decibels < -60.0f || decibels == 0.0f) {
//        return 0.0f;
//    }
//
//    return powf((powf(10.0f, 0.05f * decibels) - powf(10.0f, 0.05f * -60.0f)) * (1.0f / (1.0f - powf(10.0f, 0.05f * -60.0f))), 1.0f / 2.0f);
    return decibels;
}

@end
